//
//  macro.m
//
//  Created by yls on 14-5-4.
//  Copyright (c) 2014年 yls. All rights reserved.
//
//  iOS 相关宏定义
//

#import "macro.h"
UIView* KeyWindow_view()
{
    return [UIApplication sharedApplication].keyWindow.rootViewController.view;
}

UINavigationController* RootNavigationController()
{
    UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        return (UINavigationController*)viewController;
    }
    else if ([viewController isKindOfClass:[UITabBarController class]]){
        viewController = ((UITabBarController*)viewController).selectedViewController;
        if ([viewController isKindOfClass:[UINavigationController class]]) {
            return (UINavigationController*)viewController;
        }
    }
    return nil;
}

UIImage* UIImageNamed(NSString* name)
{
    return [UIImage imageNamed: name];
}

UIImage* UIImageWithColor(UIColor *color)
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}


UIColor* UIColorWithRGBHex(NSInteger rgbValue)
{
    return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
}
UIColor* UIColorWithRGBA(NSInteger r,NSInteger g,NSInteger b,NSInteger a)
{
    return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a];
}
UIColor* UIColorWithRGB(NSInteger r,NSInteger g,NSInteger b)
{
    return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:1.0];
}

/** 全局线程执行方法 */
void st_dispatch_async_global(dispatch_block_t block)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}

/** 主线程执行方法 */
void st_dispatch_async_main(dispatch_block_t block)
{
    dispatch_async(dispatch_get_main_queue(), block);
}

/** 主线程延时执行方法 */
void st_dispatch_async_main_after(NSTimeInterval ti, dispatch_block_t block)
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(ti * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}

/** 根据给定字体计算单位高度 */
CGFloat UnitHeightOfFont(UIFont*font)
{
    CGSize maxSize = CGSizeMake(100, 100);
    CGSize unitSize =  CGSizeOfString(@"单位",maxSize,font);
    return unitSize.height;
}

/** 根据字符串、最大尺寸、字体计算字符串最合适尺寸 */
CGSize CGSizeOfString(NSString * text, CGSize maxSize, UIFont * font)
{
    CGSize fitSize;
    if (text.length==0 || !text) {
        fitSize = CGSizeMake(0, 0);
    }else{
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            fitSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
        } else {
            fitSize = [text sizeWithFont:font constrainedToSize:maxSize];
        }
    }
    return fitSize;
}

/** 设置视图大小，原点不变 */
void SetViewSize(UIView *view, CGSize size)
{
    CGRect frame = view.frame;
    frame.size = size;
    view.frame = frame;
}

/** 设置视图宽度，其他不变 */
void SetViewSizeWidth(UIView *view, CGFloat width)
{
    CGRect frame = view.frame;
    frame.size.width = width;
    view.frame = frame;
}

/** 设置视图高度，其他不变 */
void SetViewSizeHeight(UIView *view, CGFloat height)
{
    CGRect frame = view.frame;
    frame.size.height = height;
    view.frame = frame;
}

/** 设置视图原点，大小不变 */
void SetViewOrigin(UIView *view, CGPoint pt)
{
    CGRect frame = view.frame;
    frame.origin = pt;
    view.frame = frame;
}

/** 设置视图原点x坐标，大小不变 */
void SetViewOriginX(UIView *view, CGFloat x)
{
    CGRect frame = view.frame;
    frame.origin.x = x;
    view.frame = frame;
}

/** 设置视图原点y坐标，大小不变 */
void SetViewOriginY(UIView *view, CGFloat y)
{
    CGRect frame = view.frame;
    frame.origin.y = y;
    view.frame = frame;
}

void setSubviewDelaysContentTouchesNO(UIView * v)
{
    if ([v isKindOfClass:[UIScrollView class]] || [NSStringFromClass([v class]) isEqualToString:@"UITableViewCellScrollView"]) {
        if ([v respondsToSelector:@selector(setDelaysContentTouches:)]) {
            ((UIScrollView *)v).delaysContentTouches = NO;
        }
    }
    for (UIView *obj in v.subviews)
    {
        setSubviewDelaysContentTouchesNO(obj);
    }
}


#pragma mark - 可变参数格式化
NSString* StringWithFormat(NSString*format,...)
{
    if (!format || format.length==0) {
        return nil;
    }
    //指向变参的指针
    va_list list;
    //使用第一个参数来初使化list指针
    va_start(list, format);
    NSString *str = [[NSString alloc] initWithFormat:format arguments:list];
    //结束可变参数的获取
    va_end(list);
    return str;
}



/**
 *	@brief	设置 UIFont 的缩放比例
 *
 *	@param 	font 	原始 UIFont
 *	@param 	ratio 	缩放比例
 *
 *	@return	返回设置后的 UIFont
 */
UIFont * SetFontWithBaseFont(UIFont *font , float ratio)
{
    return [UIFont fontWithName:font.fontName size:font.pointSize*ratio];
}

/**
 *	@brief	根据4\5系列的手机 320 返回大屏幕字体的大小
 *
 *	@param 	baseSize 	逻辑分辨率 320（区别设备分辨率） 机器的字体大小
 *
 *	@return	字体大小 （以 320 为逻辑分辨率 4，5 系列）
 */
float SetFontWithFontSize(float baseSize)
{
    
    return baseSize * Screen_width/320.0;
}

NSDictionary * dictionaryWithJsonString(NSString* jsonString)
{

    if (jsonString == nil) {
        return nil;
    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
    
}
NSArray * ArrayWithJsonString(NSString* jsonString)
{
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return array;
    
}


void ApplicationIconBadgeNumber(NSInteger num)
{
    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:num];
}


#pragma mark - 打开系统级应用
void ApplicationOpenURL(NSURL*url)
{
    [[UIApplication sharedApplication]openURL:url];
}
// 拨打电话
void ApplicationOpenTelWithPhoneNumber(NSString*phoneNum)
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNum]];
    ApplicationOpenURL(url);
}

// 打开应用
void ApplicationOpenURLWithString(NSString*string)
{
    NSURL *url = [NSURL URLWithString:string];
    ApplicationOpenURL(url);
}




